import { LogoutOutlined } from '@ant-design/icons';
import { history, useModel } from '@umijs/max';
import { Avatar, Dropdown, Space } from 'antd';
import { stringify } from 'querystring';
import { useCallback, type FC } from 'react';
import { flushSync } from 'react-dom';
import styles from './index.less';

interface AvatarDropdownProps {
  children?: React.ReactNode;
}

/**
 * 退出登录，并且将当前的 url 保存
 */
const loginOut = async () => {
  const loginPath = '/login';
  const { search, pathname } = window.location;
  const urlParams = new URL(window.location.href).searchParams;
  const redirect = urlParams.get('redirect');
  if (window.location.pathname !== loginPath && !redirect) {
    history.replace({
      pathname: '/login',
      search: stringify({
        redirect: pathname + search,
      }),
    });
  }
};

export const AvatarDropdown: FC<AvatarDropdownProps> = (props) => {
  const { children } = props;
  const { initialState, setInitialState } = useModel('@@initialState');
  const handleMenuClick = useCallback(
    (event: any) => {
      const { key } = event;
      if (key === 'logout') {
        flushSync(() => {
          setInitialState((preState) => {
            return {
              ...preState,
              currentUser: undefined,
            };
          });
        });
        loginOut();
        return;
      }
      history.push('/');
    },
    [setInitialState],
  );
  return (
    <Dropdown
      menu={{
        selectedKeys: [],
        onClick: handleMenuClick,
        items: [
          {
            key: 'logout',
            icon: <LogoutOutlined />,
            label: '退出登录',
          },
        ],
      }}
    >
      <div className={styles.avatar_wrap}>
        <Space>
          <Avatar
            style={{ backgroundColor: '#6743d5', verticalAlign: 'middle' }}
          >
            AD
          </Avatar>
          <span>admin</span>
        </Space>
      </div>
    </Dropdown>
  );
};

export default AvatarDropdown;
